<script setup lang="ts">
import { getCurrentInstance, ref, reactive, watch, onMounted, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
let types = []
let sizes = []
let units = []
const goods = ref([{
  type: 0,
  typeTxt: '',
  size: 0,
  sizeTxt: '',
  count: 1,
  unit: 0,
  unitTxt: '',
  price: '0.00',
  amount: '0.00'
}])
const terms = ref([])
// ----
const isMobile = /^(1[3456789]\d{9})$/
const isAmount = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{1,2}$)/
const form = reactive({
  giveName: '',
  giveLeader: '',
  giveTelphone: '',
  sentLeader: '',
  sentTelphone: '',
  sentAddress: '',
  // ----
  pickName: '',
  pickLeader: '',
  pickTelphone: '',
  takeLeader: '',
  takeTelphone: '',
  takeAddress: '',
  // ----
  totalAmount: '0.00'
})

/* ---- */
const pickerType = ref()
const pickerSize = ref()
const pickerUnit = ref()
const layer = ref()
const layerLoading = ref()
const layerBox = ref()

/* ---- */
const getFormInfo = async () => {
  // -- 获取商品型号 && 商品规格 && 商品计量单位 --
  const forTypeData = {
    params: {
      'CommonTypeSearch[dealer_id]': logUser.id,
      // --电子合同商品型号--
      'CommonTypeSearch[type]': 2,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forSizeData = {
    params: {
      'CommonTypeSearch[dealer_id]': logUser.id,
      // --电子合同商品规格--
      'CommonTypeSearch[type]': 3,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forUnitData = {
    params: {
      'CommonTypeSearch[dealer_id]': logUser.id,
      // --电子合同计量单位--
      'CommonTypeSearch[type]': 4,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('common-type/index', forTypeData),
    proxy.$Axios.get('common-type/index', forSizeData),
    proxy.$Axios.get('common-type/index', forUnitData)
  ]).then(proxy.$Axios.spread((typeData, sizeData, unitData) => {
    // --商品型号--
    const typeItems = []
    typeData.items.forEach((item, index) => {
      typeItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    types = typeItems
    // --商品规格--
    const sizeItems = []
    sizeData.items.forEach((item, index) => {
      sizeItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    sizes = sizeItems
    // --商品计量单位--
    const unitItems = []
    unitData.items.forEach((item, index) => {
      unitItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    units = unitItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --订购合同信息--
  if (proxy.$route.query.id) {
    await proxy.$http.get('contract/index', {
      params: { 'ContractSearch[id]': proxy.$route.query.id }
    }).then((res) => {
      if (Number(res.items.length) > 0) {
        const CTData = res.items[0]
        form.giveName = CTData.gh_name
        form.giveLeader = CTData.gh_leader
        form.giveTelphone = CTData.gh_telphone
        form.sentLeader = CTData.gh_wlleader
        form.sentTelphone = CTData.gh_wltelphone
        form.sentAddress = CTData.gh_address
        // ----
        form.pickName = CTData.name
        form.pickLeader = CTData.cg_leader
        form.pickTelphone = CTData.cg_telphone
        form.takeLeader = CTData.sh_leader
        form.takeTelphone = CTData.sh_telphone
        form.takeAddress = CTData.sh_address
        // ----
        const goodsItems = []
        proxy.$Myfun.getJsonData(CTData.pro_arr, (resJson) => {
          resJson.forEach((item) => {
            let forTypeTxt = ''
            let forSizeTxt = ''
            let forunitTxt = ''
            types.some((current) => {
              if (String(current.value) === String(item.type)) forTypeTxt = current.text
            })
            sizes.some((current) => {
              if (String(current.value) === String(item.size)) forSizeTxt = current.text
            })
            units.some((current) => {
              if (String(current.value) === String(item.unit)) forunitTxt = current.text
            })
            // ----
            goodsItems.push({
              type: item.type,
              typeTxt: forTypeTxt,
              size: item.size,
              sizeTxt: forSizeTxt,
              count: item.count,
              unit: item.unit,
              unitTxt: forunitTxt,
              price: item.price,
              amount: item.amount
            })
          })
        })
        if (Number(goodsItems.length) > 0) goods.value = goodsItems
        // ----
        form.totalAmount = CTData.total_amount
        // ----
        const termsItems = []
        proxy.$Myfun.getJsonData(CTData.terms, (resJson) => {
          resJson.forEach((item) => {
            termsItems.push({
              text: item.text
            })
          })
        })
        terms.value = termsItems
      }
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
const checkLimit = (event, isEmpty, reg, num, info) => {
  const curEL = event.currentTarget
  if (isEmpty && Number(curEL.value.length) === 0) return false
  if (!reg.test(curEL.value)) {
    if (info) proxy.$Myfun.forToast(layer.value, 'open', info)
    // ----
    curEL.value = num || '0.00'
    curEL.dispatchEvent(new Event('input'))
  }
}
// ----
const getAuditFun = (type, item, arr, key) => {
  switch (Number(type)) {
    case 1: {
      if (Number(item) > 0) { goods.value.splice(item, 1) } else {
        goods.value.push({
          type: 0,
          typeTxt: '',
          size: 0,
          sizeTxt: '',
          count: 1,
          unit: 0,
          unitTxt: '',
          price: '0.00',
          amount: '0.00'
        })
      }
      break
    }
    case 2: {
      const options = {
        type: 1,
        isFirst: true,
        button: ['取消', '确定'],
        initData: arr,
        yes: (result) => {
          item[key + 'Txt'] = result[0].text
          item[key] = result[0].value
        }
      }
      proxy.$Myfun.isIndepth(pickerUnit.value, 'open', options)
      break
    }
    case 3: {
      if (Number(item) >= 0) { terms.value.splice(item, 1) } else {
        terms.value.push({
          text: ''
        })
      }
      break
    }
    case 4: {
      const typeKey = {
        'type':2,//商品型号
        'size':3,//商品规格
        'unit':4,//商品计量单位
      }
      const typeText = {
        'type':'商品型号',//商品型号
        'size':'商品规格',//商品规格
        'unit':'商品计量单位',//商品计量单位
      }
      const options = {
        type: 1,
        button: ['取消', 'forSch', '确定', '新增'],
        info: {
          type: 'get',
          url: 'common-type/index',
          data: {
            params: {
              'CommonTypeSearch[dealer_id]': logUser.id,
              // --电子合同计量单位--
              'CommonTypeSearch[type]': typeKey[key],
              // ----
              sort: 'SORT_ASC',
              page: 1,
              PageSize: 1000000
            }
          },
          key: ['id', 'name']
        },
        noData: `没有找到该${typeText[key]}`,
        schKey: 'CommonTypeSearch[name]',
        yes: (result) => {
          const RJData = result[0] || {}
          item[key + 'Txt'] = RJData.text
          item[key] = RJData.value
        },
        add:() => {
          const dialogOpts = {
            type:9,
            fieldName:'name',
            button: [{
              text: '取消'
            }, {
              text: '确定',
              class: 'xw-color-24',
              callback: async (info) => {
                
                if(!info.name){
                  proxy.$Myfun.forToast(layer.value, 'open', `请输入${typeText[key]}！`)
                  return
                }
                // ----
                await proxy.$http.post('common-type/create', {
                  dealer_id: logUser.id,
                  // --电子合同商品型号--
                  type: typeKey[key],
                  // ----
                  name: info.name,
                  // ----
                  config_id: userInfo.config_id,
                  openid: userInfo.openid
                }).then((res) => {
                  layerBox.value.close()
                  proxy.$Myfun.isIndepth(pickerType.value, 'open', options)
                  proxy.$Myfun.forToast(layer.value, 'open', '添加成功！')
                }).catch((err) => { 
                  proxy.$Myfun.forToast(layer.value, 'open', err) 
                })
                
              }
            }]
          }
          proxy.$Myfun.isIndepth(layerBox.value, 'open', dialogOpts)
        }
      }
      proxy.$Myfun.isIndepth(pickerType.value, 'open', options)
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.giveName.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写供货单位！')
    return false
  }
  if (Number(form.giveLeader.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写业务负责！')
    return false
  }
  if (!isMobile.test(form.giveTelphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的业务联系电话！')
    return false
  }
  if (Number(form.sentLeader.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写物流负责！')
    return false
  }
  if (!isMobile.test(form.sentTelphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的物流联系电话！')
    return false
  }
  if (Number(form.sentAddress.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写发货地址！')
    return false
  }
  if (Number(form.pickName.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写采购单位！')
    return false
  }
  if (Number(form.pickLeader.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写采购负责！')
    return false
  }
  if (!isMobile.test(form.pickTelphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的采购联系电话！')
    return false
  }
  if (Number(form.takeLeader.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写收货负责！')
    return false
  }
  if (!isMobile.test(form.takeTelphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的收货联系电话！')
    return false
  }
  if (Number(form.takeAddress.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写收货地址！')
    return false
  }
  for (let i = 0; i < goods.value.length; i++) {
    if (Number(goods.value[i].typeTxt.length) === 0) {
      proxy.$Myfun.forToast(layer.value, 'open', '请设置第 ' + Number(i + 1) +' 个商品型号！')
      return false
    }
    if (Number(goods.value[i].sizeTxt.length) === 0) {
      proxy.$Myfun.forToast(layer.value, 'open', '请设置第 ' + Number(i + 1) +' 个商品规格！')
      return false
    }
    if (Number(goods.value[i].unitTxt.length) === 0) {
      proxy.$Myfun.forToast(layer.value, 'open', '请设置第 ' + Number(i + 1) +' 个商品计量单位！')
      return false
    }
  }
  // ----
  const forProArr = JSON.stringify(goods.value)
  // ----
  const forTerms = JSON.stringify(terms.value)
  // ----
  let forType = 'post'
  let forUrl = 'contract/create'
  let forData = {
    dealer_id: logUser.id,
    // ----
    gh_name: form.giveName,
    gh_leader: form.giveLeader,
    gh_telphone: form.giveTelphone,
    gh_wlleader: form.sentLeader,
    gh_wltelphone: form.sentTelphone,
    gh_address: form.sentAddress,
    // ----
    name: form.pickName,
    cg_leader: form.pickLeader,
    cg_telphone: form.pickTelphone,
    sh_leader: form.takeLeader,
    sh_telphone: form.takeTelphone,
    sh_address: form.takeAddress,
    // ----
    pro_arr: forProArr,
    total_amount: form.totalAmount,
    terms: forTerms,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'contract/update?id=' + proxy.$route.query.id
    forData = {
      gh_name: form.giveName,
      gh_leader: form.giveLeader,
      gh_telphone: form.giveTelphone,
      gh_wlleader: form.sentLeader,
      gh_wltelphone: form.sentTelphone,
      gh_address: form.sentAddress,
      // ----
      name: form.pickName,
      cg_leader: form.pickLeader,
      cg_telphone: form.pickTelphone,
      sh_leader: form.takeLeader,
      sh_telphone: form.takeTelphone,
      sh_address: form.takeAddress,
      // ----
      pro_arr: forProArr,
      total_amount: form.totalAmount,
      terms: forTerms,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
watch(() => goods.value, () => {
  let forTotalAmount = 0
  goods.value.forEach((item) => {
    if (Number(item.count) && Number(item.price)) {
      const forAmount = Number(item.count) * Number(item.price)
      item.amount = Number(forAmount).toFixed(2)
      // ----
      forTotalAmount += Number(forAmount)
    }
  })
  // ----
  form.totalAmount = Number(forTotalAmount).toFixed(2)
}, { deep: true })

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <div class="form-lm">供货单位信息</div>
        <li>
          <div class="form-are xw-radius-3">
            <h1>供货单位</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.giveName"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>业务负责</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请填写供货单位业务负责人姓名" v-model.trim="form.giveLeader"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.giveLeader"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>联系电话</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.giveTelphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.giveTelphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>物流负责</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请填写供货单位物流负责人姓名" v-model.trim="form.sentLeader"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.sentLeader"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>联系电话</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.sentTelphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.sentTelphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>发货地址</h1>
            <p><textarea class="tarea-H2" placeholder="" v-model.trim="form.sentAddress"></textarea></p>
          </div>
        </li>
        <div class="form-lm">采购单位信息</div>
        <li>
          <div class="form-are xw-radius-3">
            <h1>采购单位</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.pickName"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>采购负责</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请填写采购负责人姓名" v-model.trim="form.pickLeader"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.pickLeader"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>联系电话</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.pickTelphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.pickTelphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>收货负责</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请填写收货负责人姓名" v-model.trim="form.takeLeader"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.takeLeader"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>联系电话</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.takeTelphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.takeTelphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>收货地址</h1>
            <p><textarea class="tarea-H2" placeholder="" v-model.trim="form.takeAddress"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-price xw-radius-3" v-for="(item, index) in goods">
            <div class="FPE-name xw-flex xw-flex-align xw-flex-justify">
              <i>采购商品{{index + 1}}</i>
              <span class="FPE-btn fa fa-plus-square xw-color-12 xw-act" @click="getAuditFun(1)" v-if="Number(index) === 0"></span>
              <span class="FPE-btn fa fa-minus-square xw-color-13 xw-act" @click="getAuditFun(1, index)" v-else ></span>
            </div>
            <div class="FPE-type xw-flex xw-flex-align">
              <i>型号</i>
              <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model.trim="item.typeTxt" @click="getAuditFun(4, item, types, 'type')" readonly unselectable="on" onfocus="this.blur()"/></p>
              <span class="fa fa-caret-down xw-color-16"></span>
              <transition name="fade"><em class="form-L fa fa-times-circle" @click="emptyInfo" v-if="item.typeTxt"></em></transition>
            </div>
            <div class="FPE-size xw-flex xw-flex-align">
              <i>规格</i>
              <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model.trim="item.sizeTxt" @click="getAuditFun(4, item, sizes, 'size')" readonly unselectable="on" onfocus="this.blur()"/></p>
              <span class="fa fa-caret-down xw-color-16"></span>
              <transition name="fade"><em class="form-L fa fa-times-circle" @click="emptyInfo" v-if="item.sizeTxt"></em></transition>
            </div>
            <div class="FPE-unit xw-flex xw-flex-align">
              <i>数量</i>
              <p class="form-R form-Line xw-flex-W2 xw-Bfg"><input class="text" type="text" placeholder="" v-model.trim="item.count" @blur="checkLimit($event, false, isAmount, 1)"/>
              </p>
              <i class="form-L">计量单位</i>
              <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model.trim="item.unitTxt" @click="getAuditFun(4, item, units, 'unit')" readonly unselectable="on" onfocus="this.blur()"/></p>
              <span class="fa fa-caret-down xw-color-16"></span>
              <transition name="fade"><em class="form-L fa fa-times-circle" @click="emptyInfo" v-if="item.unitTxt"></em></transition>
            </div>
            <div class="FPE-price xw-flex xw-flex-align">
              <i>单价</i>
              <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model="item.price" @blur="checkLimit($event, false, isAmount)"/></p>
              <span>元</span>
              <span v-if="item.unitTxt">/{{item.unitTxt}}</span>
            </div>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>合计总金额</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.totalAmount" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span>元</span>
          </div>
        </li>
        <li>
          <div class="form-term xw-radius-3">
            <div class="FTM-name xw-flex xw-flex-align xw-flex-justify">
              <i>文字条款</i>
              <span class="FTM-btn fa fa-plus-square xw-color-12 xw-act" @click="getAuditFun(3)"></span>
            </div>
            <div class="FTM-are xw-flex" v-for="(item, index) in terms">
              <p class="form-R xw-flex-W1"><textarea class="tarea-H2" placeholder="" v-model.trim="item.text"></textarea></p>
              <span class="FTM-btn fa fa-minus-square xw-color-13 xw-act" @click="getAuditFun(3, index)"></span>
            </div>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <!-- <picker-view ref="pickerType"/> -->
    <pickermore-view ref="pickerType"/>
    <picker-view ref="pickerSize"/>
    <picker-view ref="pickerUnit"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.FPE-name i { color: #111111; font-weight: bold; }
</style>